using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLogManager;
using WJ.DataSender.Service.Commen;
using WJ.DataSender.Service.Models.ResultModel;
using WJ.DataSender.Service.UdpAndTcp.Udp;

namespace WJ.DataSender.Service
{
    public class TraceTargetsWorker : BackgroundService
    {

        /// <summary>
        /// 上报周期，通过配置文件进行配置
        /// </summary>
        private int period = CacheValues.AppsettingConfig.SendPeriod;
        public TraceTargetsWorker()
        {
            
        }

        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        public override async Task StartAsync(CancellationToken stoppingToken)
        {
            LogHelper.Info($"当前任务-[{WorkType.Targets}]-已经开始");
            await base.StartAsync(stoppingToken);
        }

        /// <summary>
        /// 正在执行
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                LogHelper.Info($"{DateTime.Now}开始启动UDP服务监听融合结果数据...");
                await Task.Run(()=> UdpReceiveService.StartReceive(stoppingToken),stoppingToken);
                
            }
            catch (Exception ex)
            {

                LogHelper.Fatal("UDP监听任务出现严重错误！！", ex);
            }
            
        }

        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            LogHelper.Info("UDP监听任务已经取消，正常退出！");
            UdpReceiveService.StopReceive();
            await base.StopAsync(stoppingToken);
        }

    }
}
